<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\tool\account\Account;
use think\Exception;
use think\facade\Cache;
use \think\model\relation\HasOne;

class Relation extends Base
{
    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    public function getCreateTimeAttr($value)
    {
        return date('Y-m-d', intval($value));
    }

    protected function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile,level_id,level_bonus_id,level_video_id,agent_level,syn_level,rec_score,village_id');
    }

    protected function fresh(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'new_uid')->with(['level' => function ($query) {
            $query->field('id,title');
        }, 'contract' => function ($query) {
            $query->field('id,title');
        }])->field('id,code,nickname,mobile,photo,breed_id,tillage_id,my_total,team_total,level_id,agent_level,contract_level_id,contract_role_id,my_dedicate,team_dedicate,village_id');
    }


    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_code -- 推荐人的编号
     * @return array
     */
    public function record($uid, $code, $parent_code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_code) {
                $p_code = $parent_code;
                $insert = [];
                while ($parent = User::where('code', $p_code)->field('id,code,parent_code')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['create_time'] = $time;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['first_uid'] = $parent_id;
                        $data['first_code'] = $parent_code;
                        $data['algebra'] = $algebra;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_code = $parent->parent_code;
                    }
                    $algebra++;
                }
                $this->saveAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }

    /**
     * 云牧场-1推荐奖/2平级奖
     */
    public static function pasturePushBonus($uid, $amount)
    {
        try {
            $list = parent::alias('a')->leftJoin('user b', 'a.uid = b.id')
                ->leftJoin('user_breed c', 'b.breed_id = c.id')
                ->where(['a.new_uid' => $uid, 'b.is_del' => 0])->where('b.breed_id', '>', 0)
                ->field('b.id, b.ranch_my_total, b.ranch_amount, b.breed_id, c.tp, c.flat_tp, a.algebra')
                ->order('a.algebra', 'asc')->select();
            if ($list) {
                $now_tp = 0;
                $now_breed = 0;
                $flat_breed = 0;
                $now_amount = 0;
                $open = Cache::get('system')['pasture_capping_open'];
                foreach ($list as $val) {
                    if ($val->breed_id > $now_breed) {
                        $real_amount = roundNum($amount * ($val->tp - $now_tp), 2);
                        if ($open == 1 && $val->breed_id == 1 && roundNum($real_amount + $val->ranch_amount, 2) > $val->ranch_my_total) {
                            $real_amount = roundNum($val->ranch_my_total - $val->ranch_amount, 2);
                        }
                        if ($real_amount > 0) {
                            self::pastureBonusEntry($val->id, $real_amount, '云牧场-推荐奖', $uid, 1);
                            User::where('id', $val->id)->inc('ranch_amount', floatval($real_amount))->update();
                        }
                        $now_tp = $val->tp;
                        $now_breed = $val->breed_id;
                        $now_amount = $real_amount;
                        $flat_breed = 0;
                    } else {
                        if ($val->breed_id == $now_breed && !$flat_breed) {
                            $real_amount = roundNum($now_amount * $val->flat_tp, 2);
                            if ($open == 1 && $val->breed_id == 1 && roundNum($real_amount + $val->ranch_amount, 2) > $val->ranch_my_total) {
                                $real_amount = roundNum($val->ranch_my_total - $val->ranch_amount, 2);
                            }
                            if ($real_amount > 0) {
                                self::pastureBonusEntry($val->id, $real_amount, '云牧场-平级奖', $uid, 2);
                                User::where('id', $val->id)->inc('ranch_amount', floatval($real_amount))->update();
                            }
                            $flat_breed++;
                        }
                    }
                }
            }
        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }

    /**
     * 云牧场-奖金入账
     */
    public static function pastureBonusEntry($uid, $amount, $intro, $source, $category)
    {
        try {
            $rate = Cache::get('system')['ranch_points_rate'];
            $account = ['ranch_bonus', 'ranch_points'];
            $real_amount_1 = roundNum($amount * (1 - $rate), 2);
            $real_amount_2 = roundNum($amount * $rate, 2);
            $real_amount = [$real_amount_1, $real_amount_2];
            foreach ($real_amount as $key => $val) {
                if ($val <= 0) {
                    unset($account[$key]);
                    unset($real_amount[$key]);
                }
            }
            if ($account && $real_amount) {
                Account::getInstance()->basics($uid, $account, $real_amount, $intro, '+')
                    ->createBonus($source, $category);
            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }

    /**
     * 专区商品奖励
     * @param $user
     * @param $op
     * @param $rate
     * @param $account
     * @param $cate
     * @param $note
     * @param false $oneself
     */
    public static function opZoneBonus($user, $op, $rate, $account, $cate, $note, $oneself = false)
    {
        if ($oneself) {
            $syn_level = $user->syn_level;
            $syn_rate = 0;
            if ($syn_level >= 3) {
                $syn_rate = $rate[$syn_level];
                $amount = roundNum($op->profit * $syn_rate, 2);
                Account::getInstance()->basics($user->id, $account, $amount, $note, '+')
                    ->setOrder($op->order_id)->createBonus($op->uid, $cate[$user->syn_level]);
            }
        } else {
            $syn_level = 2;
            $syn_rate = 0;
        }

        Relation::with('user')->where('new_uid', $user->id)
            ->field('id,uid,algebra')->order('algebra', 'asc')->select()
            ->each(function ($i) use ($op, $user, $account, $rate, $cate, $note, &$syn_level, &$syn_rate) {
                if ($i->user->syn_level > $syn_level && $rate[$i->user->syn_level] > $syn_rate) {
                    $amount = roundNum($op->profit * ($rate[$i->user->syn_level] - $syn_rate), 2);
                    if ($amount > 0) {
                        Account::getInstance()->basics($i->uid, $account, $amount, $note, '+')
                            ->setOrder($op->order_id)->createBonus($op->uid, $cate[$i->user->syn_level]);
                    }
                    $syn_level = $i->user->syn_level;
                    $syn_rate = $rate[$i->user->syn_level];
                }
            });
    }

    /**
     * 合约专区-1003市代津贴/1004推荐市代津贴/1012区代津贴/1013推荐区代津贴
     */
    public static function contractRegionSubsidy($uid, $amount)
    {
        try {
            $region_user = parent::alias('r')->leftJoin('user u', 'r.uid = u.id')
                ->where(['r.new_uid' => $uid, 'u.is_del' => 0])->whereIn('u.contract_agent_level', [1, 2, 3])
                ->field('u.id, u.parent_id, r.algebra, u.contract_agent_level')->order('r.algebra', 'asc')->find();

            if ($region_user) {
                if ($region_user->contract_agent_level == 1) {
                    $district_subsidy_rate = Cache::get('system')['district_subsidy_rate'];
                    $real_amount_1 = roundNum($amount * $district_subsidy_rate, 2);
                    $push_district_subsidy_rate = Cache::get('system')['push_district_subsidy_rate'];
                    $real_amount_2 = roundNum($amount * $push_district_subsidy_rate, 2);
                    $intro_1 = '区代津贴';
                    $intro_2 = '推荐区代津贴';
                    $category_1 = 1012;
                    $category_2 = 1013;
                } else {
                    $city_subsidy_rate = Cache::get('system')['city_subsidy_rate'];
                    $real_amount_1 = roundNum($amount * $city_subsidy_rate, 2);
                    $push_city_subsidy_rate = Cache::get('system')['push_city_subsidy_rate'];
                    $real_amount_2 = roundNum($amount * $push_city_subsidy_rate, 2);
                    $intro_1 = '市代津贴';
                    $intro_2 = '推荐市代津贴';
                    $category_1 = 1003;
                    $category_2 = 1004;
                }

                Account::getInstance()->basics($region_user->id, 'subsidy', $real_amount_1, $intro_1, '+')->createBonus($uid, $category_1);
                if ($real_amount_2 > 0) {
                    if($pid = self::getContractParentId($region_user)){
                        Account::getInstance()->basics($pid, 'subsidy', $real_amount_2, $intro_2, '+')->createBonus($uid, $category_2);
                    }
                }
            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }

    public static function getContractParentId($user): int
    {
        try{
            $p_user = User::where('id', $user->parent_id)->field('id,parent_id,contract_role_id,contract_level_id')->find();
            if($p_user){
                if($p_user->contract_role_id > 0){
                    return $p_user->id;
                }else{
                    return self::getContractParentId($p_user);
                }
            }
            return 0;
        }catch (Exception $e){
            return -1;
        }
    }

    /**
     * 合约专区-1005加盟店津贴/1006推店津贴
     */
    public static function contractStoreSubsidy($uid, $amount)
    {
        try {
            $store_subsidy_rate = Cache::get('system')['store_subsidy_rate'];
            $real_amount_1 = roundNum($amount * $store_subsidy_rate, 2);
            $push_store_subsidy_rate = Cache::get('system')['push_store_subsidy_rate'];
            $real_amount_2 = roundNum($amount * $push_store_subsidy_rate, 2);
            if ($real_amount_1 > 0) {
                $store_user = parent::alias('a')->leftJoin('user b', 'a.uid = b.id')
                    ->where(['a.new_uid' => $uid, 'b.contract_role_id' => 1, 'b.is_del' => 0])
                    ->field('b.id, b.parent_id, a.algebra')->order('a.algebra', 'asc')->find();
                if ($store_user) {
                    Account::getInstance()->basics($store_user->id, 'subsidy', $real_amount_1, '加盟店津贴', '+')
                        ->createBonus($uid, 1005);
                    if ($store_user->parent_id && $real_amount_2 > 0) {
                        Account::getInstance()->basics($store_user->parent_id, 'subsidy', $real_amount_2, '推店津贴', '+')
                            ->createBonus($uid, 1006);
                    }
                }
            }
        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }

    public static function three($user)
    {
        return self::where('uid', $user->id)->where('algebra', '<=', 3)->column('new_uid');//三代内的用户id
    }
}
